import pysrt


class VideoNode():
    def __init__(self,start=None,end=None,duration=None):
        self.start = start
        self.end = end
        self.duration = duration


def get_videonode_from_srt(srt_nodes,item):
    '''
    根据used_indexs,把对应的时间段输出
    :param srt_nodes: srt结构对象
    :param used_indexs: 使用的对应下表列表
    :return:
    '''
    video_node = VideoNode()
    used_indexs = item['origin_srt_index']
    if used_indexs:
        start = get_srt_info_from_index(srt_nodes,used_indexs[0])['start']
        end = get_srt_info_from_index(srt_nodes,used_indexs[-1])['end']


        index_num = used_indexs[-1] - used_indexs[0] +1
        if index_num == len(used_indexs):
            duration = end - start
        else:
            duration = 0.1
            for index in used_indexs:
                duration += srt_nodes[index]["duration"]

        video_node.start = start
        video_node.end = end
        video_node.duration = duration
    else:

        video_node.start = item["start"]
        video_node.end = item["end"]
        video_node.duration = sum(item['new_srt_text_parts_time'])

    return video_node

def get_srt_texts(file_name):
    srt = pysrt.open(file_name)
    output = []

    for index, (before,after) in enumerate(zip(srt.data[:-1],srt.data[1:])):
        add_delete = False
        start = before.start.ordinal / 1000
        if start< 0.5:
            start = 0

        if start !=0 and index == 0:
            info = {}
            info["start"] = 0
            info["end"] = start
            info["duration"] = start
            info["index"] = -1
            info["text"] = "$DELETE"
            info["ignore"] = True
            output.append(info)


        if (after.start.ordinal - before.end.ordinal)/1000 >=1:
            end = before.end.ordinal/1000
            add_delete = True
        else:
            end = after.start.ordinal /1000
        info = {}
        info["start"] = start
        info["end"] = end
        info["duration"] = end - start
        info["index"] = index
        info["text"] = before.text
        info["ignore"] = False
        output.append(info)
        if add_delete:
            info = {}
            info["start"] = before.end.ordinal /1000
            info["end"] = after.start.ordinal /1000
            info["duration"] = info["end"] - info["start"]
            info["index"] = -1
            info["text"] = "$DELETE"
            info["ignore"] = True
            output.append(info)

    info = {}
    info["start"] = srt.data[-1].start.ordinal/1000
    info["end"] = srt.data[-1].end.ordinal/1000
    info["duration"] = info["end"] - info["start"]
    info["index"] = len(srt.data) -1
    info["text"] = srt.data[-1].text
    info["ignore"] = False
    output.append(info)
    return output


def get_srt_texts_and_time_dict(file_name):
    srt = pysrt.open(file_name)
    output = []

    for index, (before,after) in enumerate(zip(srt.data[:-1],srt.data[1:])):
        add_delete = False
        if index == 0:
            start = 0
        else:
            start = before.start.ordinal / 1000

        if (after.start.ordinal - before.end.ordinal)/1000 >=1:
            end = before.end.ordinal/1000 + 0.1
            add_delete = True
        else:
            end = after.start.ordinal /1000

        output.append([before.text, end - start])
        if add_delete:
            delete_time = (after.start.ordinal - before.end.ordinal)/1000 - 0.1
            output.append(["$DELETE",delete_time])
    output.append([srt.data[-1].text,srt.data[-1].duration.ordinal/1000])
    return output

def caculate_reduce_time(old_video_node,new_mp3_time,heap_seconds,current_index,heap_used_time,heap_reduce_time):
    old_video_time  = old_video_node.duration
    rate_reduce_ratio = new_mp3_time / old_video_time

    print("##########################33")
    print("origin time:" + str(old_video_time))
    print("new time:" + str(new_mp3_time))
    target_time = old_video_time - new_mp3_time
    print("check reductime:" +str(target_time) )
    old_reduce_time  = sum(heap_reduce_time)
    while old_video_time > 0:
        if current_index >= len(heap_reduce_time):
            break
        currentLeftTime = heap_seconds[current_index] - heap_used_time[current_index]

        if round(old_video_time - currentLeftTime,2) >= 0:
            old_video_time -=  currentLeftTime
            heap_used_time[current_index] = heap_seconds[current_index]
            heap_reduce_time[current_index] += rate_reduce_ratio * currentLeftTime
            current_index += 1
        else:
            heap_used_time[current_index] += old_video_time
            heap_reduce_time[current_index] += rate_reduce_ratio * old_video_time
            old_video_time = 0
    print("over reductime:" + str(sum(heap_reduce_time) - old_reduce_time))

    print("current_total time:"+ str(sum([a - b for a, b in zip(heap_seconds, heap_reduce_time)])))
    return current_index

def remove_heap_less_then_half(heap_seconds_left):
    '''
    删除heap_seconds_left里面小于0.25的
    :param heap_seconds_left:每一个heap剩余的长度

    :return:
    '''

    for index,second in enumerate(heap_seconds_left):
        if second <= 0.5 and second != 0.0:
            heap_seconds_left[index -1] += second
            heap_seconds_left[index] = 0.0

    return heap_seconds_left



def get_srt_text_from_time(srt_list,search_time_start,search_time_end,search_total):
    '''
    根据起始时间和终止时间，找到最合适的srt片段
    :param srt_list:
    :param search_time_start:
    :param search_time_end:
    :param search_total:
    :return:
    '''
    before_node = None
    after_node = None
    contain_node = []

    for index, info in enumerate(srt_list):
        if info["start"] >= search_time_start and info["start"] <= search_time_end:
            contain_node.append(info)
        elif info["start"] < search_time_start and info["end"] >= search_time_start:
            contain_node.append(info)


        if contain_node:
            current_time = contain_node[-1]["end"] - contain_node[0]["start"]
            if current_time >= search_total:
                break

    if contain_node:
        before_node = srt_list[contain_node[0]["index"]-1]
        after_node = srt_list[contain_node[-1]["index"]+1]

        current_total_time = contain_node[-1]["end"] - contain_node[0]["start"]
        while search_total > current_total_time :
            contain_node.append(before_node)
            before_node = srt_list[contain_node[0]["index"]-1]
            current_total_time = contain_node[-1]["end"] - contain_node[0]["start"]
            if search_total > current_total_time :
                contain_node.append(after_node)
                after_node = srt_list[contain_node[-1]["index"]+1]
                current_total_time = contain_node[-1]["end"] - contain_node[0]["start"]

    output = {}
    if contain_node:
        output['start'] = contain_node[0]['start']
        output['duration']  = contain_node[-1]["end"] - contain_node[0]["start"]
    return output



from pysrt.srtitem import SubRipItem
def remove_duplicate_srt(text_file_name,voice_file_name):
    '''
    删除重复内容
    :param file_name:
    :return:
    '''
    srt = pysrt.open(text_file_name)
    output = []
    for item in srt.data:
        texts = []
        for s in item.text.split(" "):
            if s in texts:
                continue
            else:
                texts.append(s)
        item.text = " ".join(texts)

    j = 1
    output = []

    before_node = srt.data[0]
    for index, item in enumerate(srt.data[1:]):
        if before_node.text in item.text or item.text in before_node.text:
            before_node.end = item.end
        else:
            output.append(before_node)
            before_node = item

        if index == len(srt.data) - 2:
            output.append(before_node)

    for before,after in zip(output[:-1],output[1:]):
        if before.end > after.start:
            before.end = after.start



    word_grap = []
    for before,after in zip(output[:-1],output[1:]):
        word_grap.append(after.start - before.end)



    srt.data = output

    voice_srt = pysrt.open(voice_file_name)

    output = []


    text_index = 0
    voice_index = 0
    for info in srt.data:
        if voice_index >= len(voice_srt.data):
            output.append(info)
        else:
            check_text = []
            while voice_index < len(voice_srt.data):
                if check_node_contains(info,voice_srt.data[voice_index]):
                    if "喜欢你美丽又可爱的长相" in info.text:
                        j = 1
                    pic_text = info.text
                    voice_text = voice_srt.data[voice_index].text

                    commen_num = [i for i in pic_text if i in voice_text]
                    check_text.extend(commen_num)
                    if voice_srt.data[voice_index].end.ordinal > info.end.ordinal\
                            and voice_srt.data[voice_index].end.ordinal - 400 < info.end.ordinal:
                        voice_index += 1
                        break
                    if voice_srt.data[voice_index].end.ordinal < info.end.ordinal\
                            and voice_srt.data[voice_index].end.ordinal + 200 > info.end.ordinal:
                        voice_index += 1
                        break
                    elif voice_srt.data[voice_index].end.ordinal > info.end.ordinal:
                        break
                    else:
                        voice_index += 1
                else:
                    if voice_srt.data[voice_index].end.ordinal < info.end.ordinal:
                        voice_index += 1
                    else:
                        break
            if len(set(check_text)) /len(set(info.text)) >=0.5:
                output.append(info)
    srt.data = output
    srt.save("temp.srt")



def check_node_contains(srt_a:SubRipItem,srt_b:SubRipItem):
    x1, y1 = srt_a.start,srt_a.end
    x2, y2 = srt_b.start,srt_b.end

    common = min(y1,y2) - max(x1,x2)
    if common >= 0:
        return True
    else:
        return False

def get_srt_info_from_index(srtlist,index):
    target_node = None
    for node in srtlist:
        if node["index"] == index:
            target_node = node
            break
    return target_node







if __name__ == '__main__':
    remove_duplicate_srt(r"E:\movie\20231230-赛琳娜的黄金\jieshuo.srt",
                         r"E:\movie\20231230-赛琳娜的黄金\jieshuo_voice.srt")





